/*
	Anonymous Image Board Image Downloader - program for downloading pictures from AIB
	Copyright (C) 2011-2012 Metallhead <Metallhead@megabox.ru>

	HomePage:    http://code.google.com/p/aibid/

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "common.h"
#include "QDate"
QVector<detectorStruct> detectors;

Common::Common(QObject *parent) :
    QObject(parent)
{
}

QStringList Common::findParsers()
{
	QDir dir(filePlace(""));
	QStringList filters;
	filters << "*.xml";
	return dir.entryList(filters, QDir::Files);
}

void Common::fillParsersCombobox(QComboBox *box)
{
	QSettings settings(QCoreApplication::organizationName(),QCoreApplication::applicationName());
	createParserIfNotExists();
	QStringList parsers = findParsers();

	int added = 0;
	box->clear();
	foreach(QString parser, parsers)
	{
		box->addItem(parser);
		if(parser == settings.value("settings/parser").toString())
			box->setCurrentIndex(added);
		added++;
	}
}

QVector<detectorStruct> Common::readDetectors(QString parserName)
{
	QVector<detectorStruct> detectors;
	QFile file(filePlace(parserName));
	if(!file.exists())
	{
		qDebug() << "file" << parserName << "not found";
		return QVector<detectorStruct>();
	}
	file.open(QIODevice::ReadOnly);
	QXmlStreamReader * reader = new QXmlStreamReader(file.readAll());
	file.close();

	while(!reader->atEnd())
	{
		QXmlStreamReader::TokenType token = reader->readNext();
		if(token==QXmlStreamReader::StartDocument)
			continue;
		if(token==QXmlStreamReader::StartElement)
		{
			if(reader->name()=="detector")
			{
				detectorStruct detector;
				reader->readNext();
				while(!(reader->tokenType()==QXmlStreamReader::EndElement && reader->name() == "detector"))
				{
					if(reader->name()=="text" && detector.detector=="")
					{
						reader->readNext();
						detector.detector = reader->text().toString();
						while(reader->name()!="siteName")
							reader->readNext();
					}
					if(reader->name()=="siteName")
					{
						reader->readNext();
						detector.siteName = (bool)reader->text().toString().toInt();
						while(reader->name()!="detector")
							reader->readNext();

					}
					if(detector.detector=="")
						reader->readNext();
				}
				detectors.append(detector);
			}
		}
	}
	delete reader;
	return detectors;
}

void Common::createEmptyParserFile(QString fileName)
{
	QFile file(filePlace(fileName));
	file.open(QIODevice::WriteOnly);
	QXmlStreamWriter stream(&file);
	stream.setAutoFormatting(true);
	stream.writeStartDocument();
	stream.writeStartElement("detectors");

	stream.writeStartElement("detector");
	stream.writeTextElement("text", "test");
	stream.writeTextElement("siteName", "1");
	stream.writeEndElement();

	stream.writeEndElement();
	stream.writeEndDocument();
	file.close();
}

void Common::createParserIfNotExists()
{
	QSettings settings(QCoreApplication::organizationName(),QCoreApplication::applicationName());
	QStringList parsers = findParsers();
	if(!parsers.contains(settings.value("settings/parser").toString()))
	{
		if(parsers.count()!=0)
		{
			if(parsers.contains("parsers.xml"))
				settings.setValue("settings/parser","parsers.xml");
			else
				settings.setValue("settings/parser",parsers.first());
		}
		else
		{
			createEmptyParserFile("parsers.xml");
			parsers.append("parsers.xml");
			settings.setValue("settings/parser","parsers.xml");
		}
	}
}

QString Common::filePlace(QString file)
{
	QDir dir(QDesktopServices::storageLocation(QDesktopServices::DataLocation));
	file = QDir::toNativeSeparators(file);
	if(file==""||file.endsWith(QDir::separator()))
	{
		dir.cd(file);
		return dir.absolutePath();
	}
	else
		return dir.absoluteFilePath(file);
}
#ifdef Q_OS_MAC
QString Common::packagePlace(QString file)
{
	QDir dir(QCoreApplication::applicationDirPath());
	file = QDir::toNativeSeparators(file);
	if(file==""||file.endsWith(QDir::separator()))
	{
		dir.cd(file);
		return dir.absoluteFilePath();
	}
	else
		return dir.absoluteFilePath(file);
}
#endif
uint Common::getHash(QString fileName)
{
	QFile file(fileName);
	file.open(QIODevice::ReadOnly);
	QByteArray data = file.readAll();
	file.close();
	uint hash = qHash(data);
	return hash;
}
void Common::deleteLogs()
{
	QDir dir(filePlace("logs/"));
	QStringList logs = dir.entryList(QDir::Files);

	foreach(QString log, logs)
	{
		QDate date = QDate::fromString(log, "d.M.yyyy");
		if(date.daysTo(QDate::currentDate()) > 7 )
			dir.remove(log);
	}
}
